package edu.hawaii.ics414;

import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Initializes the screen for creating a new account.
 * 
 * @author Matthew Mizumoto
 * 
 */

public class NewAccountView extends Activity {

  /*
   * Called when the activity is first created.
   */
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.new_account);

    Button button = (Button) this.findViewById(R.id.createAccountButton);

    /*
     * Initializes the create account button to have it try to create a new account.
     */
    button.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        EditText firstNameText = (EditText) findViewById(R.id.firstNameText);
        EditText lastNameText = (EditText) findViewById(R.id.lastNameText);
        EditText emailText = (EditText) findViewById(R.id.emailText);
        EditText usernameText = (EditText) findViewById(R.id.usernameText);
        EditText passwordText = (EditText) findViewById(R.id.passwordText);
        EditText passwordConfirmText = (EditText) findViewById(R.id.passwordAgainText);

        String firstName = firstNameText.getText().toString();
        String lastName = lastNameText.getText().toString();
        String email = emailText.getText().toString();
        String username = usernameText.getText().toString();
        String password = passwordText.getText().toString();
        String passwordConfirm = passwordConfirmText.getText().toString();

        if (!password.equals(passwordConfirm)) {
          Toast.makeText(NewAccountView.this, "Please Reenter Password", Toast.LENGTH_LONG).show();
        }
        else {
          try {
            String createSuccess =
                new CreateUser().execute(username, password, firstName, lastName, email).get(5,
                    TimeUnit.SECONDS);
            boolean created = Boolean.parseBoolean(createSuccess.trim());
            if (created) {
              Toast.makeText(NewAccountView.this,
                  "Account Successfully Created \n Welcome " + username, Toast.LENGTH_LONG).show();
            }
            else {
              Toast.makeText(NewAccountView.this, createSuccess.trim(), Toast.LENGTH_LONG).show();
            }
          }
          catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    });

  }
}
